package com.tnovoselec.android.ui.imagegallery;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.tnovoselec.android.ui.MyViewPager;


public class ImageGallery extends MyViewPager {

    private TouchImageView v;

    public ImageGallery(Context context) {
	this(context, null);
    }

    public ImageGallery(Context context, AttributeSet attrs) {
	super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
	super.onInterceptTouchEvent(ev);
	return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
	switch (ev.getAction()) {
	    case MotionEvent.ACTION_DOWN:
		View touchedView = null;
		for (int i = 0; i < getChildCount(); i++) {
		    final View v = getChildAt(i);
		    final Rect r = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
		    r.offset(-getScrollX(), 0);
		    if (r.contains((int) ev.getX(), (int) ev.getY())) {
			touchedView = v;
			break;
		    }
		}
		final View view = getTouchImageView(touchedView);
		if (view != null && view instanceof TouchImageView) {
		    v = (TouchImageView) view;
		}
	    default:
		if (v != null) {

		    v.setHorizontalScrollEnabled((getScrollX() + getWidth()) % getWidth() == 0);
		    v.dispatchTouchEvent(ev);
		    if (v.isOnHorizontalEdge()) {
			return super.onTouchEvent(ev);
		    }
		}
		return true;
	}

    }

    private TouchImageView getTouchImageView(View view) {
	TouchImageView imageview = null;
	if (view instanceof TouchImageView) {
	    imageview = (TouchImageView) view;
	}
	if (view instanceof ViewGroup) {
	    final ViewGroup viewgroup = (ViewGroup) view;
	    for (int i = 0; i < viewgroup.getChildCount(); i++) {
		imageview = getTouchImageView(viewgroup.getChildAt(i));
		if (imageview != null) {
		    break;
		}
	    }
	}
	return imageview;
    }

}
